from PIL import Image
import numpy as np
# 读取图像并灰度
base_url = './assets/img/'
head_url = base_url + 'head.jpg'
def In1():
    pil_img = Image.open(head_url).convert('L')
    pil_img.save('out.jpg')
# In1()
# 转换格式
import os
def In2():
    out_file = os.path.splitext(head_url)[0] + '.png'
    try:
        Image.open(head_url).save(out_file)
    except:
        print('err')
# In2()
def In3():
    pil_img = Image.open(head_url)
    # 创建缩略图
    # pil_img.thumbnail((128,128))
    box = (100, 100, 400, 400)
    # 复制粘贴图像区域
    ## region = pil_img.crop(box)
    ## region.save(base_url+'cut1.jpg')
    ## region.transpose(Image.ROTATE_180).save(base_url+'rotate180.jpg')
    # pil_img.paste(region, box)
    # 调整尺寸和旋转
    out = pil_img.resize((128,128))
    out.rotate(45).save(base_url+'resize_rotate.jpg')
# In3()

# Matplotlib
# 绘制图像点线
import pylab as plb
def In3():
    img = np.array(Image.open(head_url).convert('L'))
    plb.figure()  # 新建图像
    plb.gray()  # 不使用颜色信息
    plb.contour(img, origin='image')    #在原点左上角显示轮廓图像
    plb.axis('equal')
    plb.axis('off')
    plb.figure()  # 新建图像
    plb.hist(img.flatten(), 128)
    plb.show()
# In3()
def In4():
    img = np.array(Image.open(head_url))
    plb.imshow(img)
    print('click 3 points')
    x = plb.ginput(3)
    print('you click {}'.format(x))
    plb.show()
# In4()
# 灰度变换
def In5():
    im = np.array(Image.open(head_url).convert('L'))
    im2 = 254.5 - im
    im3 = (100/255) * im + 100 # 像素值变换到100-200之间
    im4 = 255.0 * (im/255.0)**2 # 像素值求平方
    out_im = Image.fromarray(plb.uint8(im4))
    out_im.save(base_url+'out.jpg')
# In5()
# 图像缩放
def im_resize(im, sz):
    pil_im = Image.fromarray(plb.uint8(im))
    return np.array(pil_im.resize(sz))
# 直方图均衡化
def histeq(im, nbr_bins=256):
    # 对灰度图像进行直方图均衡化
    im_hist, bins = plb.histogram(im.flatten(), nbr_bins)
    print(bins)
    cdf = im_hist.cumsum() 
    cdf = 255 * cdf / cdf[-1] # 归一化
    im2 = plb.interp(im.flatten(), bins[:-1], cdf)
    return im2.reshape(im.shape), cdf
def In6():
    im = np.array(Image.open(head_url).convert('L'))
    im2, cdf = histeq(im)
    print(cdf)
    Image.fromarray(plb.uint8(im2)).save(base_url+'in6.1.jpg')
# In6()

# 图像平均
'''可以图像降噪'''
def compute_average(imlist):
    averageim = np.array(Image.open(imlist[0], 'f'))
    for imname in imlist[1:]:
        try:
            averageim += np.array(Image.open(imname))
        except:
            print(imname+'...skipped')
    averageim /= len(imlist)
    return np.array(averageim, 'uint8')

# 图像主成分分析

# 高斯模糊
from scipy.ndimage import filters
def In9():
    im = np.array(Image.open(head_url))
    im2 = plb.zeros(im.shape)
    for i in range(3):
        im2[:,:,i] = filters.gaussian_filter(im[:,:,i], 5)
    im2 = plb.uint8(im2)
    im2 = np.array(im2, 'uint8')
    Image.fromarray(im2).save(base_url+'in9.1.jpg')
# In9()

# 图像导数
'''
高斯导数滤波器
'''

# 形态学：对象计数
from scipy import ndimage as ndi
def In10():
    im = np.array(Image.open(head_url).convert('L'))
    im = 1*(im<128)
    labels, nbr_objects = ndi.label(im)
    print('number of onjects: {}'.format(nbr_objects))
    print(labels)
    im_open = ndi.binary_opening(im,np.ones((9,5)),iterations=2)
    labels_open, nbr_objects_open = ndi.label(im_open)
    print('number of objs_open: {}'.format(nbr_objects_open))
# In10()

# 图像去噪